package com.martin.lib_base.net

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.LongSerializationPolicy
import com.martin.lib_base.BuildConfig
import com.martin.lib_base.constant.ConstantKey
import com.martin.lib_base.impl.HttpLogImpl
import com.martin.lib_base.net.adapter.NullAdapterFactory
import com.martin.lib_base.net.interceptor.HeaderInterceptor
import com.martin.lib_base.net.interceptor.NoEncryptionInterceptor
import com.martin.lib_base.net.interceptor.SignAndEncryptionInterceptorLive
import dev.utils.DevFinal
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import kotlin.properties.Delegates

/**
 * @author ：Martin
 * @data : 2018/6/21 15:39
 */
object NetApply {

    // 超时时间
    private const val DEFAULT_TIMEOUT: Long = 20000L

    // 接口对象
    var api: Api by Delegates.notNull()

    // JSON解析器
    val gson: Gson = GsonBuilder()
        // 设置日期格式
        .setDateFormat(DevFinal.TIME.yyyyMMddHHmmss_HYPHEN)
        //类型处理
        .registerTypeAdapterFactory(NullAdapterFactory())
        .setLongSerializationPolicy(LongSerializationPolicy.STRING)
        // 序列化null
        .serializeNulls()
        .create()

    init {
        // 初始化日志拦截器
        val logInterceptor = HttpLoggingInterceptor(HttpLogImpl())
        // 设置日志拦截器的日志级别
        if (BuildConfig.env == ConstantKey.RELEASE) {
            logInterceptor.level = HttpLoggingInterceptor.Level.NONE
        } else {
            logInterceptor.level = HttpLoggingInterceptor.Level.BODY
        }

        // 初始化OkHttp
        val client = OkHttpClient.Builder()
            // 连接超时时间
            .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
            // 读取超时时间
            .readTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
            // 写入超时时间
            .callTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
            // 添加日志拦截器
//            .addInterceptor(logInterceptor)
            // Header拦截器
            .addInterceptor(HeaderInterceptor())
        // 加密拦截器
        if (BuildConfig.ENCRYPT_TYPE == ConstantKey.RELEASE) {
            client.addInterceptor(SignAndEncryptionInterceptorLive())
        } else {
            client.addInterceptor(NoEncryptionInterceptor())
        }

        // 初始化Retrofit
        val retrofit = Retrofit.Builder()
            // 设置OkHttp
            .client(client.build())
            // 设置网络请求的Url地址
            .baseUrl(Api.BASE_URL)
            // 添加Gson解析器
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()

        api = retrofit.create(Api::class.java)
    }

}